#pragma once
#include <iostream>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "Log.hpp"
#define BUFFER_SIZE 1024
#define DEFAULT_PROT 8888
#define EXITSIGNAL "exit"

using func_t = std::function<std::string(const std::string &, const std::string &, in_port_t)>;
std::string default_func(const std::string &message, const std::string &ip, in_port_t port)
{
    std::cout << "Client[" << ip << ":" << port << "] Massage# " << message << std::endl;
    return message;
}

using namespace LogModule;

class UDPServer
{
public:
    UDPServer(in_port_t port = DEFAULT_PROT, func_t func = default_func)
        : isrunning(false), _port(port), _func(func)
    {
        // 面向数据报, UDP套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: 套接字创建失败! ";
            exit(errno);
        }
        // 初始化需要绑定的网络信息
        struct sockaddr_in addr;
        bzero(&addr, sizeof(addr));
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(_port);

        int n = bind(_sockfd, (struct sockaddr *)&addr, sizeof(addr));
        if (n != 0)
        {
            LOG(LogLevel::FATAL) << "bind: 网络信息绑定失败! ";
            exit(errno);
        }
        LOG(LogLevel::INFO) << "UDPServer: UDP套接字(sockfd=" << _sockfd << ")创建成功";
    }
    ~UDPServer()
    {
        close(_sockfd);
    }
    UDPServer(const UDPServer&) = delete;
    UDPServer& operator=(const UDPServer&) = delete;
    void Start()
    {
        isrunning = true;
        char buffer[BUFFER_SIZE];
        while (isrunning)
        {
            // 等待客户端发送信息
            struct sockaddr_in client_addr;
            socklen_t client_addr_len = sizeof(client_addr);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&client_addr, &client_addr_len);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string client_ip = inet_ntoa(client_addr.sin_addr);
                in_port_t client_port = ntohs(client_addr.sin_port);
                std::string ret_message = _func(buffer, client_ip, client_port);
                sendto(_sockfd, ret_message.c_str(), ret_message.size(), 0, (struct sockaddr *)&client_addr, client_addr_len);
            }
        }
    }

private:
    int _sockfd;
    in_port_t _port;
    bool isrunning;
    func_t _func;
};